package com.atguigu.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.ExcelSubjectData;
import com.atguigu.serviceedu.entity.excel.SubjectExcelListener;
import com.atguigu.serviceedu.mapper.EduSubjectMapper;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.atguigu.serviceedu.vo.OneLevelSubject;
import com.atguigu.serviceedu.vo.TwoLevelSubject;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2021-12-18
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file, EduSubjectService subjectService) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, ExcelSubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e) {
            e.printStackTrace();
            throw new GuliException(20002,"添加课程分类失败");
        }
    }

    @Override
    public List<OneLevelSubject> selectAllSubject() {
        List<EduSubject> eduSubjects = this.baseMapper.selectList(new QueryWrapper<EduSubject>().eq("parent_id", 0));
        List<OneLevelSubject> oneLevelSubjects = eduSubjects.stream().map(item -> {
            OneLevelSubject oneLevelSubject = new OneLevelSubject();
            oneLevelSubject.setId(item.getId());
            oneLevelSubject.setTitle(item.getTitle());
            List<EduSubject> subjects = this.baseMapper.selectList(new QueryWrapper<EduSubject>().eq("parent_id", item.getId()));
            List<TwoLevelSubject> twoLevelSubjects = subjects.stream().map(sub -> {
                TwoLevelSubject twoLevelSubject = new TwoLevelSubject();
                twoLevelSubject.setId(sub.getId());
                twoLevelSubject.setTitle(sub.getTitle());
                return twoLevelSubject;
            }).collect(Collectors.toList());
            oneLevelSubject.setChildren(twoLevelSubjects);
            return oneLevelSubject;
        }).collect(Collectors.toList());
        return oneLevelSubjects;
    }

}
